package org.liang.family_manager.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
public class FileStorageService {
    @Value("${app.upload.dir}")
    private String uploadDir;

    @Value("${app.upload.nginx-url}")
    private String nginxUrl;

    public String storeFile(MultipartFile file, Long memberId) throws IOException {
        // 生成唯一文件名
        String fileName = "member_" + memberId  +
                         "." + StringUtils.getFilenameExtension(file.getOriginalFilename());
        
        // 创建目标路径
        Path targetPath = Paths.get(uploadDir).resolve(fileName).normalize();
        Files.createDirectories(targetPath.getParent());
        
        // 保存文件
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
        }
        
        // 返回通过Nginx访问的URL
        return nginxUrl + fileName;
    }
}